//
//  LYTextField.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/20.
//

import UIKit
import SnapKit

class LYTextField: UIView {
    
    // MARK: - UI Elements
    private let backgroundImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.isUserInteractionEnabled = true
        return iv
    }()
    
    let textField: UITextField = {
        let tf = UITextField()
        tf.borderStyle = .none
        tf.font = UIFont.systemFont(ofSize: 16)
        return tf
    }()
    
    // MARK: - Properties
    var placeholder: String? {
        didSet {
            textField.placeholder = placeholder
        }
    }
    
    var keyboardType: UIKeyboardType = .default {
        didSet {
            textField.keyboardType = keyboardType
        }
    }
    
    var maxLength: Int = 0 {
        didSet {
            if maxLength > 0 {
                textField.delegate = self
                textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
            }
        }
    }
    
    // MARK: - Initialization
    init(backgroundImage: UIImage? = nil) {
        super.init(frame: .zero)
        setupUI()
        backgroundImageView.image = backgroundImage
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    private func setupUI() {
        addSubview(backgroundImageView)
        addSubview(textField)
        
        backgroundImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        textField.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(16)
        }
    }
    
    func setLeftView(view: UIView, width: CGFloat) {
        let container = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 50))
        container.addSubview(view)
        view.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.trailing.equalToSuperview()
        }
        textField.leftView = container
        textField.leftViewMode = .always
    }
}

// MARK: - 输入长度限制实现
extension LYTextField: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard maxLength > 0 else { return true }
        
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        
        return updatedText.count <= maxLength
    }
}

@objc extension LYTextField {
    func textFieldDidChange() {
        guard maxLength > 0, let text = textField.text, text.count > maxLength else { return }
        textField.text = String(text.prefix(maxLength))
    }
}

